<template>
  <div class="password-container">
    <el-card class="password-card">
      <template #header>
        <div class="card-header">
          <span class="title">修改密码</span>
          <div class="back-link">
            <router-link to="/user/profile">
              <el-button link type="primary">
                <el-icon><ArrowLeft /></el-icon>返回个人信息
              </el-button>
            </router-link>
          </div>
        </div>
      </template>

      <el-form :model="passwordForm" :rules="rules" ref="formRef" label-width="120px" class="password-form">
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入当前密码" show-password />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
          <div class="form-tip">密码长度应为8-20个字符，包含字母、数字和特殊字符</div>
        </el-form-item>

        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">确认修改</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="password-tips">
        <h3>密码修改说明：</h3>
        <ul>
          <li>密码修改成功后，系统将自动退出登录，请使用新密码重新登录</li>
          <li>为保证账号安全，请使用强密码并定期更换密码</li>
          <li>强密码建议：至少8位，包含大小写字母、数字和特殊字符</li>
        </ul>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowLeft } from "@element-plus/icons-vue";
import { changePassword } from "@/api/user";
import { logout } from "@/utils/auth";

const router = useRouter();
const formRef = ref(null);
const loading = ref(false);

// 表单数据
const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 验证新密码强度
const validatePassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入密码"));
    return;
  }

  if (value.length < 8 || value.length > 20) {
    callback(new Error("密码长度应为8-20个字符"));
    return;
  }

  // 检查密码复杂度：至少包含字母、数字和特殊字符
  const hasLetter = /[a-zA-Z]/.test(value);
  const hasNumber = /\d/.test(value);
  const hasSpecial = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value);

  if (!(hasLetter && hasNumber && hasSpecial)) {
    callback(new Error("密码应包含字母、数字和特殊字符"));
    return;
  }

  callback();
};

// 验证确认密码
const validateConfirmPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请再次输入新密码"));
    return;
  }

  if (value !== passwordForm.newPassword) {
    callback(new Error("两次输入的密码不一致"));
    return;
  }

  callback();
};

// 表单验证规则
const rules = {
  oldPassword: [{ required: true, message: "请输入当前密码", trigger: "blur" }],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { validator: validatePassword, trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入新密码", trigger: "blur" },
    { validator: validateConfirmPassword, trigger: "blur" },
  ],
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    // 二次确认
    try {
      await ElMessageBox.confirm("修改密码后将自动退出登录，需要重新登录，是否继续?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      });

      loading.value = true;
      const response = await changePassword({
        password: passwordForm.oldPassword,
        newPassword: passwordForm.newPassword,
      });

      if (response.success) {
        ElMessage.success("密码修改成功，请重新登录");
        // 退出登录
        setTimeout(() => {
          logout();
          router.push("/login");
        }, 1500);
      } else {
        ElMessage.error(response.message || "密码修改失败");
      }
    } catch (cancelError) {
      // 用户取消操作
      console.log("用户取消修改密码");
    }
  } catch (error) {
    console.error("表单验证失败", error);
  } finally {
    loading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
};
</script>

<style scoped>
.password-container {
  padding: 20px;
}

.password-card {
  max-width: 600px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.back-link {
  display: flex;
  align-items: center;
}

.password-form {
  margin-top: 20px;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 6px;
  line-height: 1.5;
}

.password-tips {
  margin-top: 30px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.password-tips h3 {
  margin-top: 0;
  margin-bottom: 12px;
  font-size: 16px;
  font-weight: 600;
  color: #606266;
}

.password-tips ul {
  margin: 0;
  padding-left: 20px;
}

.password-tips li {
  margin-bottom: 8px;
  line-height: 1.6;
  color: #606266;
}
</style>
